import 'dart:convert';
import 'package:base_flutter/base_flutter.dart';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:ls_work/a_elder/page/elder_search_page.dart';
import 'package:ls_work/a_yyt/models/sporadic_income_entity.dart';
import 'package:ls_work/a_yyt/page/add_sporadic_ncome_page.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/resources.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';

import '../../util/flat_button.dart';



class HomeSporadicIncomePage extends StatefulWidget {
  @override
  HomeSporadicIncomePageState createState() => HomeSporadicIncomePageState();
}

class HomeSporadicIncomePageState extends State<HomeSporadicIncomePage> {
  EasyRefreshController _controller = EasyRefreshController();
  int _page = 1;
  List<SporadicIncomeInfo> _dataList = [];

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fectDataList();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('零星收入'),
        elevation: 0.5,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Expanded(
            child: EasyRefresh(
              enableControlFinishLoad: true,
              onRefresh: _onRefresh,
              onLoad: _loadMore,
              controller: _controller,
              emptyWidget: _dataList.length > 0
                  ? null
                  : Container(
                      child: Center(
                        child: Text(
                          '暂无数据',
                          style: TextStyles.textGray16,
                        ),
                      ),
                    ),
              child: ListView.separated(
                itemCount: _dataList.length,
                itemBuilder: (_, index) {
                  return ExpansionTile(
                    title: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          _dataList[index].source == 1
                              ? '${_dataList[index].expenseItemName ?? ''}'
                              : '${_dataList[index].elderHumanName ?? ''}',
                          style: TextStyles.textDark20,
                        ),
                        Gaps.hGap15,
                        Gaps.hGap15,
                        Text(
                          '${_dataList[index].money ?? ''} 元',
                          style: TextStyle(color: Colors.red, fontSize: 18),
                        ),
                        Expanded(
                          child: Gaps.hGap15,
                        ),
                        Text('${_dataList[index].createdDate ?? ''}',
                            style: TextStyles.textGray16),
                      ],
                    ),
                    children: <Widget>[
                      Container(
                        alignment: Alignment.centerLeft,
                        padding: EdgeInsets.fromLTRB(15, 0, 15, 8),
                        child: Text.rich(TextSpan(children: [
                          TextSpan(
                            text: '收费类型：',
                            style: TextStyles.textGray16,
                          ),
                          TextSpan(
                            text: '${_dataList[index].sourceDesc}',
                            style: TextStyles.textDark16,
                          ),
                        ])),
                      ),
                      Container(
                        alignment: Alignment.centerLeft,
                        padding: EdgeInsets.fromLTRB(15, 0, 15, 8),
                        child: Text.rich(TextSpan(children: [
                          TextSpan(
                            text: '收费项目：',
                            style: TextStyles.textGray16,
                          ),
                          TextSpan(
                            text: '${_dataList[index].expenseItemName}',
                            style: TextStyles.textDark16,
                          ),
                        ])),
                      ),
                      Container(
                        alignment: Alignment.centerLeft,
                        padding: EdgeInsets.fromLTRB(15, 0, 15, 8),
                        child: Text.rich(TextSpan(children: [
                          TextSpan(
                            text: '项目单价：',
                            style: TextStyles.textGray16,
                          ),
                          TextSpan(
                            text: TextUtil.isEmpty(
                                    _dataList[index].billingUnitName)
                                ? '${_dataList[index].price ?? 0.0}元'
                                : '${_dataList[index].price ?? 0.0}元/${_dataList[index].billingUnitName}',
                            style: TextStyles.textDark16,
                          ),
                        ])),
                      ),
                      Container(
                        alignment: Alignment.centerLeft,
                        padding: EdgeInsets.fromLTRB(15, 0, 15, 8),
                        child: Text.rich(TextSpan(children: [
                          TextSpan(
                            text: '使用数量：',
                            style: TextStyles.textGray16,
                          ),
                          TextSpan(
                            text: '${_dataList[index].num}',
                            style: TextStyles.textDark16,
                          ),
                        ])),
                      ),
                      Container(
                        alignment: Alignment.centerLeft,
                        padding: EdgeInsets.fromLTRB(15, 0, 15, 8),
                        child: Text.rich(TextSpan(children: [
                          TextSpan(
                            text: '实收价格：',
                            style: TextStyles.textGray16,
                          ),
                          TextSpan(
                            text: '${_dataList[index].money} 元',
                            style: TextStyles.textDark16,
                          ),
                        ])),
                      ),
                      Container(
                        alignment: Alignment.centerLeft,
                        padding: EdgeInsets.fromLTRB(15, 0, 15, 8),
                        child: Text.rich(TextSpan(children: [
                          TextSpan(
                            text: '    经办人：',
                            style: TextStyles.textGray16,
                          ),
                          TextSpan(
                            text: '${_dataList[index].createdByName ?? ''}',
                            style: TextStyles.textDark16,
                          ),
                        ])),
                      ),
                    ],
                  );
                },
                separatorBuilder: (_, int index) => Gaps.line,
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.fromLTRB(15, 8, 15, 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                FlatsButton(
                  color: Colors.blue,
                  highlightColor: Colors.blue[700]!,
                  child: Text("增加机构内费用"),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(25.0),
                  ),
                  onPressed: () {
                    AppNavigator.push(
                      context,
                      ElderSearchPage(isSelected: true),
                    );
                  },
                ),
                FlatsButton(
                  color: Colors.blue,
                  highlightColor: Colors.blue[700]!,
                  child: Text("增加机构外费用"),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(25.0)),
                  onPressed: () {
                    AppNavigator.push(
                      context,
                      AddHomeSporadicIncomePage(
                        type: 1,
                        callBack: _onRefresh,
                      ),
                    );
                  },
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Future _onRefresh() async {
    _page = 1;
    await _fectDataList();
  }

  Future _loadMore() async {
    _page++;
    await _fectDataList();
  }

  ///获取数据
  _fectDataList() {
    var map = {
      'page': _page,
      'rows': 20,
    };
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(HttpApi.expenseMealsList, data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            SporadicIncomeEntity model =
                SporadicIncomeEntity.fromJson(map['data']);
            if ((model.rows??[]).length > 0) {
              _controller.finishLoad(
                  success: true, noMore: (model.rows??[]).length != 20);
              if (_page == 1) {
                /// 刷新
                _dataList.clear();
                _dataList.addAll(model.rows??[]);
              } else {
                _dataList.addAll(model.rows??[]);
              }
            } else {
              if (_page == 1) {
                /// 没有数据
                _dataList.clear();
              }
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }
}
